# Maintainer: Chocobo1

_realname=zstd
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.4.5
pkgrel=1
pkgdesc="Zstandard - Fast real-time compression algorithm (mingw-w64)"
arch=('any')
url='https://facebook.github.io/zstd/'
license=('BSD')
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-cmake")
source=(${_realname}-${pkgver}.tar.gz::"https://github.com/facebook/${_realname}/archive/v${pkgver}.tar.gz"
        install-pkgconfig.patch
        zstd-1.4.0-fileio-mingw.patch
        zstd-1.4.0-fix-build-pzstd.patch
        zstd-1.4.5-fix-install-shared-library.patch)
sha256sums=('734d1f565c42f691f8420c8d06783ad818060fc390dee43ae0a89f86d0a4f8c2'
            '9a8864dd11ad6f1eaf1e11ee19adfdbc4e023f20b14b429b8af2b387ffffdef4'
            '210e57fc4bff62e1af1ca8a3da3960de32a91255ba62b057c6bed5b3a7ebb3d5'
            '5095624a5d59054053a257c6b8ec2156b410a44e0e491b259c276c4b7650f499'
            '31e071e5e7e75dcecfd1eafd07a0b6bb5cfbcdc5b5c172478b73c1915d2cdc06')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -Np1 -i "${srcdir}/install-pkgconfig.patch"
  patch -Np1 -i "${srcdir}/zstd-1.4.0-fileio-mingw.patch"
  patch -Np1 -i "${srcdir}/zstd-1.4.0-fix-build-pzstd.patch"
  patch -Np1 -i "${srcdir}/zstd-1.4.5-fix-install-shared-library.patch"
}

build() {
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  mkdir -p "${srcdir}"/build-${CARCH} && cd "${srcdir}"/build-${CARCH}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi
  
    MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -G'MSYS Makefiles' \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DZSTD_BUILD_CONTRIB=ON \
      ../${_realname}-${pkgver}/build/cmake

  make
}


package() {
  cd "${srcdir}"/build-${CARCH}
  make install DESTDIR="${pkgdir}"

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"

  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|$(cygpath -m ${MINGW_PREFIX})|${MINGW_PREFIX}|g" -i "${pcfile}"
  done
}
